package cn.odore.org.controller;

import cn.odore.basic.util.AjaxResult;
import cn.odore.basic.util.PageList;
import cn.odore.org.domain.Department;
import cn.odore.org.query.DepartmentQuery;
import cn.odore.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门接口
 */
@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @PutMapping
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult save(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.add(department);
            } else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("保存失败" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "部门删除",notes = "通过id删除部门")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            departmentService.del(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询部门",notes = "通过id查询一条部门数据")
    public Department getById(@PathVariable("id") Long id){
        return departmentService.getById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询所有部门",notes = "查询出所有部门数据")
    public List<Department> getAll(){
        return departmentService.getAll();
    }

    @PostMapping
    @ApiOperation(value = "分页查询部门",notes = "分页查询部门的数据")
    public PageList<Department> list(@RequestBody DepartmentQuery query){
        return departmentService.list(query);
    }

    @PatchMapping
    public AjaxResult del(@RequestBody List<Long> ids){
        try {
            departmentService.patchDel(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败" + e.getMessage());
        }
    }

    @GetMapping("/getTree")
    public List<Department> getTree(){
        return departmentService.getDeptTree();
    }


}
